package com.example.day_blog.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;

import java.security.Key;
import java.util.Date;
import java.util.Map;

/**
 * @author starsea
 * @date 2024-01-19 14:24
 */
@Slf4j
@RestController
public class JwtUtils {
    //限制时间
    private static final long expiration =30*60*1000;
    private static final String secretString="UCj3yTwo3YKOtkvLpR7rc36qD5Zwofno1v+hQplh604=";
    private static final Key key= Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));
    public static String getToken(Map<String,Object> claim)
    {
        String token= Jwts.builder()
                .setClaims(claim)
                .setExpiration(new Date(System.currentTimeMillis()+expiration))
                .signWith(key)
                .compact();
        //生成一个token
        return token;
    }
    //校验
    public static Claims  parseToken(String token)
    {
      if(!StringUtils.hasLength(token))
      {
          return null;
      }
        JwtParser build= Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims=null;
        try {
            claims=build.parseClaimsJws(token).getBody();

        }catch (Exception e)
        {
            log.error("解析token出错"+token);
        }
        return claims;
    }
    //从token中获取id
    public static Integer getUserIdFromToken(String token)
    {
        Claims claims=parseToken(token);
        if(claims==null)
        {
            return null;
        }
        return (Integer) claims.get("id");
    }
}
